package org.ko.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public final class JSONConverter {

//	private static final Gson GSON = new Gson();
//	private static final Gson PRETTY_GSON = new Gson();
	private static final Gson GSON = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
	private static final Gson PRETTY_GSON = new GsonBuilder().serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss").setPrettyPrinting().create();
	
//	@SuppressWarnings("unchecked")
//	public static <T> T jsonToObject(String text, TypeReference<T> ref) throws Exception {
//		ObjectMapper mapper = createMapper();
//		
//		return (T) mapper.readValue(text.getBytes(), ref);
//	}

	public static <T> T jsonToObject(String json, Class<T> type) {
		return GSON.fromJson(json, type);
	}

	/**
	 * 调用示例 WeibaOutput<WeibaOrder> output = JsonConverter.jsonToObject(json, new TypeToken<WeibaOutput<WeibaOrder>>() {});
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T jsonToObject(String json, TypeToken<T> type){
		return GSON.fromJson(json, type.getType());
	}
	
	public static String objectToJson(Object obj, String dateFormat) {
		return new GsonBuilder().serializeNulls().setDateFormat(dateFormat).create().toJson(obj);
	}
	
	public static String objectToJson(Object obj) {
		return obj != null ? objectToJson(obj, false) : null;
	}

	public static String objectToJson(Object obj, boolean prettyPrint) {
		String json = null;
		
		if(obj != null){
			json = prettyPrint ? PRETTY_GSON.toJson(obj) : GSON.toJson(obj);
		}
		
		return json;
	}
	
	private JSONConverter() {};
	
//	private static ObjectMapper createMapper() {
//		return new ObjectMapper()
//				.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true)
//				.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//	}
}
